package easier.camera.x;

import android.annotation.SuppressLint;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysis.Analyzer;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.Preview;
import androidx.camera.core.UseCase;
import androidx.camera.core.VideoCapture;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

public abstract class CameraXManager {

    private final LifecycleOwner mOwner;

    public CameraXManager( Context context, LifecycleOwner lifecycle ) {

        mOwner = lifecycle;
        initCamera( context );
    }

    private void initCamera( Context context ) {

        ListenableFuture< ProcessCameraProvider > instance = ProcessCameraProvider.getInstance( context );
        instance.addListener( new Runnable() {
            @Override
            public void run() {

                try {
                    ProcessCameraProvider cameraProvider = instance.get();
                    CameraSelector backCamera = provideCameraSelector();
                    UseCase[] useCases = buildUseCases();

                    cameraProvider.unbindAll();
                    cameraProvider.bindToLifecycle( mOwner, backCamera, useCases );

                } catch ( ExecutionException | InterruptedException e ) {
                    e.printStackTrace();
                }
            }
        }, ContextCompat.getMainExecutor( context ) );
    }

    /**
     * @return 提供相机
     */
    @NonNull
    protected CameraSelector provideCameraSelector() {

        return CameraSelector.DEFAULT_BACK_CAMERA;
    }

    /**
     * @return 提供使用用例
     */
    protected abstract UseCase[] buildUseCases();

    /**
     * 快捷方法,构建预览
     *
     * @param previewView 预览界面
     *
     * @return 预览用例
     */
    public Preview buildPreviewCase( PreviewView previewView ) {

        Preview preview = new Preview.Builder().build();
        preview.setSurfaceProvider( previewView.getSurfaceProvider() );
        return preview;
    }

    /**
     * @return 快捷方法, 构建拍照
     */
    public ImageCapture buildImageCaptureCase() {

        return new ImageCapture.Builder().build();
    }

    @SuppressLint( "RestrictedApi" )
    public VideoCapture buildVideoCaptureCase() {

        return new VideoCapture.Builder().build();
    }

    public ImageAnalysis buildImageAnalysisCase( @NonNull Analyzer analyzer ) {

        ImageAnalysis analysis = new ImageAnalysis.Builder().build();
        analysis.setAnalyzer( Executors.newSingleThreadExecutor(), analyzer );
        return analysis;
    }
}
